import logging
from elasticsearch import Elasticsearch
import requests
success = 200
internal_error = 500
class SearchAPI(object):
    def __init__(cls, index_name, index_type, ip="119.91.216.229"):
        '''
        :param index_name: 索引名称
        :param index_type: 索引类型
        '''
        cls.index_name = index_name
        cls.index_type = index_type
        # 无用户名密码状态
        cls.es = Elasticsearch([ip], port=9200)
        # 用户名密码状态
        # cls.es = Elasticsearch([ip], http_auth=('elastic', 'password'), port=9200)

    @classmethod
    def Index_Data(cls):
        '''
        数据存储到es
        :return:
        '''
        list = [
            {"date": "2017-09-13",
             "source": "慧聪网",
             "link": "http://info.broadcast.hc360.com/2017/09/130859749974.shtml",
             "keyword": "电视",
             "title": "付费 电视 行业面临的转型和挑战"
             },
            {"date": "2017-09-13",
             "source": "中国文明网",
             "link": "http://www.wenming.cn/xj_pd/yw/201709/t20170913_4421323.shtml",
             "keyword": "电视",
             "title": "电视 专题片《巡视利剑》广获好评：铁腕反腐凝聚党心民心"
             }
        ]
        # 标准化doc_type应该是index_type，但一开始命名为 doc，故针对该网站搜索节点更改为doc
        with open ('json',"w")as f:
            list = f.readline()
            print(list)
        for item in list:
            res = cls.es.index(index=cls.index_name, doc_type=cls.index_type, body=item)
            print(res['created'])

    @classmethod
    def Searchapi(cls, request):
        """
        搜索接口，调用ES查找文件名称，并使其关键词并高亮

        """
        logging.debug("working on Search_api")
        # es = Elasticsearch()    # 默认连接本地elasticsearch
        #keywords = requests.value.get('keywords')#接收关键字信息
        es = Elasticsearch(['119.91.216.229'], port=9200)  # 连接本地9200端口
        #关键字符
        keyword = '碳排放' #测试用例
        query = {
                   'query': {
                        'match': {
                            'name': keyword
                        }
                    }
                }#测试用例
        code = success
        #标准化输出，可直接套入flask框架中使用
        # query ={
        #            'query': {
        #                 'match': {
        #                     'name': keywords
        #                 }
        #             }
        #         }
        result = es.search(index='records', doc_type='doc', body=query)
        print(result)
        name = []
        if result['hits']['total'] == 0:
            print("No matching data")
        else:
            hits = result['hits']['hits']
            for i in range(0, len(hits)):
                #匹配名称内字符，为其关键词前后加<em></em>
                individual_name = hits[i]['_source']['name']
                #当匹配到关键字符，对该名称做修改
                if individual_name.find(keyword):
                    #两个方法，一个是在里面匹配后替换，直接用keyword替换即可
                    str = "<em>"+individual_name[individual_name.find(keyword):individual_name.find(keyword)+len(keyword)]+"</em>"
                    individual_name = individual_name.replace(keyword, str)
                name.append(individual_name)
        print(name)
        resp = {
                    'code': code,
                    'data': name,
                }
        #return jsonify(name)

